// pages/openBookcase/openBookcase.js
const request = require('../../utils/request.js');
//获取应用实例
const app = getApp()
var varName;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    progressValue: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      caseId: options.id
    })
  },
  onShow: function () {
    var that = this;
    that.getToken();
  },

  getToken: function () {
    var that = this;
    // 获取本地存储中的token
    wx.getStorage({
      key: 'token',
      success: function (res) {//有该数据
        console.log(res.data)
        that.setData({
          token: res.data
        })
        that.progress(10);
      },
      fail: function (res) {
        console.log(res.data)
        //调用授权方法-设置token
        app.getUserInfo();
      }
    })
  },

  //开门
  openDoor: function () {
    var that = this;
    var postData = {};
    postData.session_id = that.data.token;
    postData.bid = that.data.caseId;
    console.log(postData)

    request.openDoor(postData,
      (res) => {
        console.log(res.data)
        if (parseInt(res.data) == 1) {
          that.progress(4);
        }else{
          wx.showModal({
            title: '温馨提示',
            content: '请求失败，请返回重新扫码',
            confirmText: "回首页",
            showCancel: "false",
            confirmColor: "#FF0000",
            success: function (res) {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        }
      })
  },
  //进度条事件
  progress: function (tempNum) {
    var that = this;
    var animation_interval = 200, n = 100;
    var step = 1;
    var animation = function () {
      if (step <= n) {
        // console.log(step)
        that.setData({
          progressValue: step
        })
        step = step + tempNum;
      } else {
        clearInterval(varName);
        wx.redirectTo({
          url: '../openBookcase/onOpen/onOpen?caseId=' + that.data.caseId,
        })
      }
    };
    varName = setInterval(animation, animation_interval);
  },

})